package com.atguigu.tingshu.account.consumer;


import com.atguigu.tingshu.account.service.UserAccountDetailService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单支付完成后账户的后续处理：记录消费
 */
@Component
@Log4j2
public class OrderAfterPaidAccountConsumer {
    @Autowired
    private UserAccountDetailService userAccountDetailService;

    /**
     * 账户充值成功后添加用户账户明细
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "order_after_paid_account_queue")
    public void orderAfterPaidAccount(Channel channel, Message message){
        // Message = orderNo
        String orderNo = new String(message.getBody());
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 账户充值成功后记录用户账户明细
            userAccountDetailService.addUserAccountDetail(orderNo);
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            if (messageProperties.getRedelivered()){
                log.error("用户账户明细记录失败,失败的原因为:" + e.getMessage() + ",订单号为:" + orderNo);
                channel.basicReject(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,true);
            }
        }

    }

}
